const express = require('express');
const router = express.Router();
const Shortmes = require("./shortmes");
const Regmes = require("./regmes");
const Article = require("./article");
const Product = require("./product");
const Chatmes = require("./chatmes");
const validate = require("../public/javascripts/validate");
const valiMes = require("../public/javascripts/validateShortmes");
const valiArt = require("../public/javascripts/validateArticle");
const valiPro = require("../public/javascripts/validateProduct");
const date = require("../public/javascripts/date");

function isLoged(req,res,next){
  if(req.session.user){
    next();
  }else{
    return res.send("请先登录。");
  }
}



//发布留言
router.post("/shortmes",isLoged,async function(req, res) {
  const {
    content,
    vnum
  } = req.body;
  const user = res.locals.user = req.session.user;
  const loginname = user.loginname;
  const firstnum = req.session.firstnum;
  const secondnum = req.session.secondnum;
  const errors = valiMes(content,vnum,firstnum,secondnum);
  if (errors){
    console.log(errors);
    return res.send(errors);
  }else{
    var nowDate = new Date();
    var doc = new Shortmes({
      loginname,
      content,
      createTime:nowDate,
      S_Time:date(nowDate,'-')
    });
    console.log(doc);
    await doc.save();
    console.log("留言存入成功");
    return res.send("留言存入成功");
  }
});

//删除留言
router.post("/shortmes/delete",isLoged,async function (req,res) {
  const {
    mesLogName,
    mesLogTime
    } = req.body;
  const logedname = req.session.user.loginname;
  try {
    const logedmes = await Regmes.findOne({loginname:logedname});
    console.log("logedmes=",logedmes);
    if (logedmes.loginname === mesLogName || logedmes.admin === true){
      await Shortmes.remove().where("loginname").eq(mesLogName).where("S_Time").eq(mesLogTime);
      console.log("留言已删除。");
      return res.send("留言已删除。");
    }else{
      console.log("抱歉，您不是管理员，不能删除他人留言。");
      return res.send("抱歉，您不是管理员，不能删除他人留言。");
    }
  } catch (e) {
    console.log(e);
    res.send(e.name + ": " + e.message);
  }
});

//发布文章
router.post("/article", isLoged,async function(req, res) {
  const {
    title,
    content,
    vnum
  } = req.body;
  const user = res.locals.user = req.session.user;
  const loginname = user.loginname;
  const firstnum = req.session.firstnum;
  const secondnum = req.session.secondnum;
  const errors = valiArt(title,content,vnum,firstnum,secondnum);
  if (errors){
    console.log(errors);
    return res.send(errors);
  }else{
    var nowDate = new Date();
    const doc = new Article({
        loginname,
        title,
        content,
        createTime:nowDate,
        updateTime:nowDate,
        S_Time:date(nowDate,'-'),
        accessNum:1
    });
    console.log(doc);
    await doc.save();
    console.log("文章发布成功");
    return res.send("文章发布成功");
  }
});

//阅读全文
router.get("/article/:id/detail",async function (req,res) {
    const doc = await Article.findById(req.params.id);
    doc.accessNum += 1;
    await doc.save();
    const user =   res.locals.user = req.session.user||null;
    req.session.firstnum = res.locals.firstnum = Math.round(Math.random() * 10);
    req.session.secondnum = res.locals.secondnum = Math.round(Math.random() * 10);
    return res.render("showarticle", {doc});
});

//删除文章
router.post("/article/delete",isLoged,async function (req,res) {
  const artLogId = req.body.artLogId;
  const logedname = req.session.user.loginname;
  try {
    const logedmes = await Regmes.findOne({loginname:logedname});
    console.log("logedmes=",logedmes);
    const doc = await Article.findById(artLogId);
    console.log("doc=",doc);
    if (logedmes.loginname === doc.loginname || logedmes.admin === true){
      await doc.remove();
      console.log("文章已删除。");
      return res.send("文章已删除。");
    }else{
      console.log("抱歉，您不是管理员，不能删除他人文章。");
      return res.send("抱歉，您不是管理员，不能删除他人文章。");
    }
  } catch (e) {
    console.log(e);
    res.send(e.name + ": " + e.message);
  }
});

//编辑文章--在文章列表处
router.post("/article/edit",isLoged,async function (req,res) {
  const artLogId = req.body.artLogId;
  const logedname = req.session.user.loginname;
  try {
    const logedmes = await Regmes.findOne({loginname:logedname});
    console.log("logedmes=",logedmes);
    const doc = await Article.findById(artLogId);
    console.log("doc=",doc);
    if (logedmes.loginname === doc.loginname){    //只有文章作者可以二次编辑
      console.log("文不厌改,精益求精。");
      return res.send("文不厌改,精益求精。");
    }else{
      console.log("抱歉，您不能更改他人文章。");
      return res.send("抱歉，您不能更改他人文章。");
    }
  } catch (e) {
    console.log(e);
    res.send(e.name + ": " + e.message);
  }
});
//编辑文章--在阅读全文处
router.post("/article/:id/edit",isLoged,async function (req,res) {
  const {
    artLogId,
    title,
    content,
    vnum
  } = req.body;
  const user = res.locals.user = req.session.user;
  const logedname = req.session.user.loginname;
  const firstnum = req.session.firstnum;
  const secondnum = req.session.secondnum;
  const errors = valiArt(title,content,vnum,firstnum,secondnum);
  if (errors){
    console.log(errors);
    return res.send(errors);
  }else{
    try {
      const logedmes = await Regmes.findOne({loginname:logedname});
      console.log("logedmes=",logedmes);
      const doc = await Article.findById(artLogId);
      console.log("doc=",doc);
      if (logedmes.loginname === doc.loginname){    //只有文章作者可以二次编辑
        var nowDate = new Date();
        doc.title = title;
        doc.content = content;
        doc.updateTime = nowDate;
        doc.S_Time = date(nowDate,'-');
        doc.accessNum += 1;
        await doc.save();
        console.log("文章已更改。");
        return res.send("文章已更改。");
      }else{
        console.log("抱歉，您不能编辑他人文章。");
        return res.send("抱歉，您不能编辑他人文章。");
      }
    } catch (e) {
      console.log(e);
      res.send(e.name + ": " + e.message);
    }
  }
});

//发布产品
router.post("/product", isLoged, async function(req, res) {
  const {
    pname,
    pimgsrc,
    pprice,
    pdescription,
    vnum
  } = req.body;
  const user = res.locals.user = req.session.user;
  const logedname = req.session.user.loginname;
  const firstnum = req.session.firstnum;
  const secondnum = req.session.secondnum;
  const errors = valiPro(pname,pimgsrc,pprice,pdescription,vnum,firstnum,secondnum);
  if (errors){
    console.log(errors);
    return res.send(errors);
  }else{
    try {
      const logedmes = await Regmes.findOne({loginname:logedname});
      console.log("logedmes=",logedmes);
      if (logedmes.admin === true){       //只有管理员可以发布产品
        var nowDate = new Date();
        const doc = new Product({
            pname,
            pimgsrc,
            pprice,
            pdescription,
            createTime:nowDate,
            updateTime:nowDate,
            S_Time:date(nowDate,'-'),
            accessNum:1
        });
        console.log(doc);
        await doc.save();
        console.log("产品已成功发布");
        return res.send("产品已成功发布");
      }else{
        console.log("抱歉，您不是管理员，不能发布产品。");
        return res.send("抱歉，您不是管理员，不能发布产品。");
      }
    } catch (e) {
      console.log(e);
      res.send(e.name + ": " + e.message);
    }
  }
});

//删除产品
router.post("/product/delete",isLoged,async function (req,res) {
  const proLogId = req.body.proLogId;
  const logedname = req.session.user.loginname;
  try {
    const logedmes = await Regmes.findOne({loginname:logedname});
    console.log("logedmes=",logedmes);
    const doc = await Product.findById(proLogId);
    console.log("doc=",doc);
    if (logedmes.admin === true){
      await doc.remove();
      console.log("产品已删除。");
      return res.send("产品已删除。");
    }else{
      console.log("抱歉，您不是管理员，不能删除已发布的产品。");
      return res.send("抱歉，您不是管理员，不能删除已发布的产品。");
    }
  } catch (e) {
    console.log(e);
    res.send(e.name + ": " + e.message);
  }
});

//产品详情
router.get("/product/:id/detail",async function (req,res) {
    const doc = await Product.findById(req.params.id);
    doc.accessNum += 1;
    await doc.save();
    const user =   res.locals.user = req.session.user||null;
    req.session.firstnum = res.locals.firstnum = Math.round(Math.random() * 10);
    req.session.secondnum = res.locals.secondnum = Math.round(Math.random() * 10);
    return res.render("showproduct", {doc});
});

//编辑产品--在产品列表处
router.post("/product/edit",isLoged,async function (req,res) {
  const proLogId = req.body.proLogId;
  const logedname = req.session.user.loginname;
  try {
    const logedmes = await Regmes.findOne({loginname:logedname});
    console.log("logedmes=",logedmes);
    if (logedmes.admin === true){
      console.log("欢迎更改产品信息。");
      return res.send("欢迎更改产品信息。");
    }else{
      console.log("抱歉，您不是管理员，不能编辑已发布的产品。");
      return res.send("抱歉，您不是管理员，不能编辑已发布的产品。");
    }
  } catch (e) {
    console.log(e);
    res.send(e.name + ": " + e.message);
  }
});

//编辑产品--在产品详情处
router.post("/product/:id/edit",isLoged,async function (req,res) {
  const {
    proLogId,
    pname,
    pimgsrc,
    pprice,
    pdescription,
    vnum
  } = req.body;
  const user = res.locals.user = req.session.user;
  const logedname = req.session.user.loginname;
  const firstnum = req.session.firstnum;
  const secondnum = req.session.secondnum;
  const errors = valiPro(pname,pimgsrc,pprice,pdescription,vnum,firstnum,secondnum);
  if (errors){
    console.log(errors);
    return res.send(errors);
  }else{
    try {
      const logedmes = await Regmes.findOne({loginname:logedname});
      console.log("logedmes=",logedmes);
      const doc = await Product.findById(proLogId);
      console.log("doc=",doc);
      if (logedmes.admin === true){
        var nowDate = new Date();
        doc.pname = pname;
        doc.pimgsrc = pimgsrc;
        doc.pprice = pprice;
        doc.pdescription = pdescription;
        doc.updateTime = nowDate;
        doc.S_Time = date(nowDate,'-');
        doc.accessNum += 1;
        console.log(doc);
        await doc.save();
        console.log("产品相关信息已成功更改");
        return res.send("产品相关信息已成功更改");
      }else{
        console.log("抱歉，您不是管理员，不能编辑已发布的产品。");
        return res.send("抱歉，您不是管理员，不能编辑已发布的产品。");
      }
    } catch (e) {
      console.log(e);
      res.send(e.name + ": " + e.message);
    }
  }
});

//聊天室
router.get('/chatroom', isLoged,async function(req, res, next) {
  const user = res.locals.user = req.session.user;
  res.render('chatroom');
});

router.post("/chatroom",isLoged,async function(req, res) {
  const { content } = req.body;
  const user = res.locals.user = req.session.user;
  const loginname = user.loginname;

  var nowDate = new Date();
  var doc = new Chatmes({
    loginname,
    content,
    createTime:nowDate,
    S_Time:date(nowDate,'-')
  });
  console.log(doc);
  await doc.save();
  console.log("发送成功");
  return res.send("发送成功");
});


router.get("/changeReg", function(req, res) {
  const user = res.locals.user = req.session.user;
  req.session.firstnum = res.locals.firstnum = Math.round(Math.random() * 10);
  req.session.secondnum = res.locals.secondnum = Math.round(Math.random() * 10);
  return res.render("changeReg", {user});
});

router.post("/changeReg", async function(req, res) {
  const {
    loginname,
    password,
    admin,
    confirm,
    vnum
  } = req.body;
  const logedname = req.session.user.loginname;
  const firstnum = req.session.firstnum;
  const secondnum = req.session.secondnum;
  const errors = validate(loginname,password,confirm,vnum,firstnum,secondnum);
  if(errors){
    console.log(errors);
    res.send(errors);
  }else{
    try {
      const logedmes = await Regmes.findOne({loginname:logedname});
      console.log("logedmes=",logedmes);
      if (logedmes.loginname === loginname || logedmes.admin === true){
        var reg = await Regmes.findOne({loginname:loginname});
        console.log("oldreg=",reg);
        reg.loginname = loginname,
        reg.password = password,
        reg.admin = admin
        console.log("newregs=",reg);
        await reg.save();
        console.log("用户信息更改成功");
        res.send("用户信息更改成功。");
      }else{
        console.log("抱歉，您不是管理员，无权更改他人注册信息。");
        res.send("抱歉，您不是管理员，无权更改他人注册信息。");
      }
    }catch(e){
      console.log("此用户名尚未注册。" + e.name + ": " + e.message);
      res.send("此用户名尚未注册。" + e.name + ": " + e.message);
    }
  }
});

router.get("/logout", function(req, res) {
  const user = res.locals.user = req.session.user = undefined;
  res.redirect("../../");
});

module.exports = router;
